/*
 * @Author: your name
 * @Date: 2022-10-18 10:09:16
 * @LastEditTime: 2022-11-07 18:55:00
 * @LastEditors: DESKTOP-I9IOH8S
 * @Description: index-评论模块方法集和
 * @FilePath: \myTencentClassComment\js\modules\index\comment_mocule.js
 */

// 初始化分页模块
var initPageBtns = function (pages, curPage) {
    var oBtnBox = $get('.J_btnBox')[0];

    render();

    function pageBtnTpl(type, pageNum) {
        switch (type) {
            case 'prev':
                if (curPage == 1) {
                    return '<span class="dir-btn prev-btn disabled"><i class="fa fa-angle-left"></i></span>';
                } else {
                    return '<a href="javascript:;" class="dir-btn prev-btn" data-field="prev"><i class="fa fa-angle-left" data-field="prev"></i></a>';
                }
            case 'next':
                if (curPage == pageNum) {
                    return '<span class="dir-btn next-btn disabled"><i class="fa fa-angle-right"></i></span>';
                } else {
                    return '<a href="javascript:;" class="dir-btn next-btn" data-field="next"><i class="fa fa-angle-right" data-field="next"></i></a>';
                }
            case 'btn':
                if (curPage == pageNum) {
                    return '<span class="page-btn page-btn-cur">' + pageNum + '</span>';
                } else {
                    return '<a href="javascript:;" class="page-btn" data-page="' + pageNum + '" data-field="btn">' + pageNum + '</a>';
                }
            case 'points':
                return '<span class="points">... </span>';
        }
    }

    function setNumBtn(startNum, stopNum) {
        var temp = '';
        for (var i = startNum; i <= stopNum; i++) {
            temp += pageBtnTpl('btn', i, curPage);
        }
        return temp;
    }

    function render() {
        var btnGroup = '';

        btnGroup += pageBtnTpl('prev', pages, curPage);
        if (pages > 7) {
            if (curPage >= 1 && curPage < 3) {
                btnGroup += setNumBtn(1, 3, curPage);
                btnGroup += pageBtnTpl('points');
                btnGroup += setNumBtn(pages - 1, pages, curPage);
            } else if (curPage >= 3 && curPage < 5) {
                btnGroup += setNumBtn(1, curPage + 1, curPage);
                btnGroup += pageBtnTpl('points');
                btnGroup += setNumBtn(pages - 1, pages, curPage);
            } else if (curPage >= 5 && curPage < pages - 3) {
                btnGroup += setNumBtn(1, 2, curPage);
                btnGroup += pageBtnTpl('points');
                btnGroup += setNumBtn(curPage - 1, curPage + 1, curPage);
                btnGroup += pageBtnTpl('points');
                btnGroup += setNumBtn(pages - 1, pages, curPage);
            } else if (curPage >= pages - 3 && curPage < pages) {
                btnGroup += setNumBtn(1, 2, curPage);
                btnGroup += pageBtnTpl('points');
                btnGroup += setNumBtn(curPage - 1, pages, curPage);
            } else if (curPage === pages) {
                btnGroup += setNumBtn(1, 2, curPage);
                btnGroup += pageBtnTpl('points');
                btnGroup += setNumBtn(curPage - 2, pages, curPage);
            }
        } else {
            btnGroup += setNumBtn(1, pages, curPage);
        }
        btnGroup += pageBtnTpl('next', pages, curPage);

        oBtnBox.innerHTML = btnGroup;
    }
}

// 初始化评论模块
var initCommentModule = (function (initPageBtns) {

    // 获取节点
    // 隐藏对话框
    var oCommentEditBoard = $get('.J_commentEditBoard')[0],
        //星星列表里的所有项目
        oHoverStars = $get('.J_hoverStar'),
        // 星星旁边的文字描述盒子
        oStarTip = $get('.J_starTip')[0],
        // 提交评论按钮
        oSubmitBtn = $get('.J_submitBtn')[0],
        //文本区域下面的数字提示 0/1000
        oTxtCount = $get('.J_txtCount')[0],
        // 输入文本区域
        oEditTxt = $get('.J_editTxt')[0],
        // 评论导航栏按钮的集和
        oTabRadioItems = $get('.tab-radio'),
        // 获取列表加载图标
        oLoading = $get('.J_loading')[0],
        // 课程列表
        oCommentList = $get('.J_commentList')[0],
        // 好评度
        oStatisticsNum = $get('.J_statisticsNum')[0],
        // 分页按钮栏
        oBtnBox = $get('.J_btnBox')[0],

        // 错误信息 模板
        WarningTip = $get('#J_warningTip').innerHTML,
        // 评论 模板
        ItemTpl = $get('#J_itemTpl').innerHTML,
        // 追加评论 模板
        AddCommentTpl = $get('#J_addCommentTpl').innerHTML,

        // 延时器
        t = null,

        datas = {
            // 初始化星星数量
            starNum: 5,
            // 延迟时间
            delayTime: 500,
            // 列表ID
            fieldId: 0,
            // 分页
            pageNum: 0,
            // 页数
            pages: 0
        };



    // 接口
    var APIs = {
        submitComment: 'http://localhost/api_for_study/index.php/Comment/submitComment',
        getComments: 'http://localhost/api_for_study/index.php/Comment/getComments'
    }

    return {
        //点击 立即评论按钮 显示评论对话框
        openBoard: function () {
            //显示评论对话框盒子
            oCommentEditBoard.style.display = 'block';
        },

        //点击 x按钮 隐藏评论对话框
        closeBoard: function () {
            this._restoreBoardStatus();
            //隐藏评论对话框盒子
            oCommentEditBoard.style.display = 'none';
            // 输入文本框的内容清空
            // oEditTxt.value = '';
        },

        //填写评论
        editInput: function () {
            var val = trimSpace(oEditTxt.value),
                valLen = val.length;

            oTxtCount.innerHTML = valLen;
            if (valLen >= 15 && valLen <= 1000) {
                // this.submitBtnStateChange(false);
                this.submitBtnChange({
                    txtChange: false,
                    isDisabled: false
                });

            } else {
                // this.submitBtnStateChange(true);
                this.submitBtnChange({
                    txtChange: false,
                    isDisabled: true
                });
            }
        },

        //五星选择
        starsHover: function (e) {
            var e = e || window.e,
                tar = e.target || e.srcElement,
                tagName = tar.tagName.toLowerCase();

            if (tagName === 'i') {
                var thisIdx = [].indexOf.call(oHoverStars, tar),
                    len = oHoverStars.length,
                    thisStarItem = oHoverStars[thisIdx],
                    item;

                oStarTip.innerHTML = thisStarItem.getAttribute('data-title');
                datas.starNum = thisStarItem.getAttribute('data-count');

                for (var i = 0; i < len; i++) {
                    item = oHoverStars[i];
                    i <= thisIdx ? item.className = 'fa fa-star J_hoverStar active' :
                        item.className = 'fa fa-star J_hoverStar';
                }
            }
        },

        // 提交评论
        submitComment: function (userId) {
            var val = oEditTxt.value,
                valLen = trimSpace(val).length,
                _self = this;

            if (valLen >= 15 && valLen < 1000) {
                xhr.ajax({
                    url: APIs.submitComment,
                    type: 'POST',
                    data: {
                        userId: userId,
                        starNum: datas.starNum,
                        comment: val
                    },
                    success: function (data) {
                        var errorCode = data.error_code,
                            oFirstCommentItem = oCommentList.getElementsByClassName('comment-item')[0];

                        _self.submitBtnChange({
                            txtChange: true,
                            isDisabled: false
                        });


                        // 用延迟，是在网络时候可以告诉用户现在需要等待
                        t = setTimeout(function () {
                            _self._restoreBoardStatus();
                            _self.closeBoard();
                            clearTimeout(t);

                            if (errorCode === '10010') {
                                alert("您已对该课程进行评价，谢谢您！");
                                return;
                            }


                            if (data.res.is_add_comment == '0') {
                                // 不是追加评论时 将新增评论渲染到评论列表
                                if (oFirstCommentItem) {
                                    oCommentList.insertBefore(_self._commentItemTplReplace(data.res), oFirstCommentItem);
                                } else {
                                    oCommentList.innerHTML = '';
                                    oCommentList.appendChild(_self._commentItemTplReplace(data.res));
                                }
                            } else if (data.res.is_add_comment == '1') {
                                // 追加评论时 将追加评论渲染到评论列表
                                _self._appendAddComment(data.res);
                            }

                            _self.setTabRadioNum(data.num);
                        }, datas.delayTime);

                    },

                    error: function () {
                        alert('对不起，提交评论失败，请重试！');
                    }
                });
            }
        },

        // 评论导航栏 切换评论
        radioTabClick: function (e) {
            var e = e || window.e,
                tar = e.target || e.srcElement,
                className = tar.className;

            if (className == 'radio-icon' || className == 'radio-txt') {
                var oParent = tar.parentNode,
                    len = oTabRadioItems.length,
                    item;

                datas.fieldId = oParent.getAttribute('data-id');

                for (var i = 0; i < len; i++) {
                    item = oTabRadioItems[i];
                    item.className = 'tab-radio';
                }

                oParent.className += ' cur';
                datas.pageNum = 1;
                this.getComments({
                    fieldId: datas.fieldId,
                    pageNum: datas.pageNum
                });
            }
        },

        // 设置评论导航栏 各类评论数目
        setTabRadioNum: function (arr) {
            var oRadioCount = 0;

            arr.forEach(function (elem, idx) {
                oRadioCount = oTabRadioItems[idx].getElementsByClassName('radio-count')[0];
                oRadioCount.innerHTML = elem;
            });
            21212
            oStatisticsNum.innerHTML = arr[0] > 0
                ? Math.ceil(arr[1] / arr[0] * 100) + '%'
                : '-';
        },

        // 获取评论列表
        getComments: function (opt) {
            var _self = this,
                fieldId = opt.fieldId,
                pageNum = opt.pageNum;

            xhr.ajax({
                url: APIs.getComments,
                type: 'POST',
                data: {
                    field: fieldId,
                    page: (pageNum - 1)
                },
                success: function (data) {
                    var num = data.num,
                        pages = data.pages,
                        data = data.res,
                        len = data.length;

                    oLoading.style.display = 'block';

                    t = setTimeout(function () {
                        _self.setTabRadioNum(num);
                        oCommentList.innerHTML = '';
                        oLoading.style.display = 'none';
                        clearTimeout(t);

                        if (len <= 0) {
                            _self._setWarningTip('暂无评论');
                            return;
                        }

                        oCommentList.appendChild(_self.renderList(data));

                        if (pages > 1) {
                            initPageBtns(pages, pageNum);
                        } else {
                            oBtnBox.innerHTML = '';
                        }

                    }, datas.delayTime);

                },

                error: function () {
                    _self._setWarningTip('获取评论失败！');
                }
            });
        },

        // 点击分页按钮 -事件代理
        pageBtnClick: function (e) {
            var e = e || window.e,
                tar = e.target || e.srcElement,
                fieldBtn = tar.getAttribute('data-field');

            switch (fieldBtn) {
                case 'btn':
                    datas.pageNum = parseInt(tar.getAttribute('data-page'));
                    break;
                case 'prev':
                    datas.pageNum -= 1;
                    break;
                case 'next':
                    datas.pageNum += 1;
                    break;
            }

            this.getComments({
                fieldId: datas.fieldId,
                pageNum: datas.pageNum
            });
        },

        // 渲染评论列表
        renderList: function (data) {
            var frag = document.createDocumentFragment(),
                _self = this;

            data.forEach(function (elem) {
                frag.appendChild(_self._commentItemTplReplace(elem));
            });

            return frag;
        },

        // 增加评论 不刷新页面时增加
        _appendAddComment: function (data) {
            var oCommentItems = $get('.comment-item'),
                itemsLen = oCommentItems.length,
                addDataId = data.add_id,
                dataId,
                item;

            for (var i = 0; i < itemsLen; i++) {
                item = oCommentItems[i];
                dataId = item.getAttribute('data-id');

                if (dataId == addDataId) {
                    item.innerHTML += AddCommentTpl.replace(/{{(.*?)}}/gim, function (node, key) {
                        return {
                            comment: data.comment,
                            uptime: getDateTime(data.uptime, 'dateTime')
                        }[key];
                    });
                }
            }
        },

        // 评论 模板替换
        _commentItemTplReplace: function (data) {
            var dom = document.createElement('div'),
                starNum = data.star_num,
                count = 0;

            dom.className = 'comment-item';
            dom.setAttribute('data-id', data.id);
            dom.innerHTML = ItemTpl.replace(/{{(.*?)}}/gim, function (node, key) {
                key === 'isActive' && count++;

                return {
                    avatar: 'img/' + data.avatar,
                    nickname: data.nickname,
                    isActive: starNum >= count ? 'active' : '',
                    comment: data.comment,
                    uptime: getDateTime(data.uptime, 'dataTime')
                }[key];
            });


            if (data.add_comment) {
                dom.innerHTML += AddCommentTpl.replace(/{{(.*?)}}/gim, function (node, key) {
                    return {
                        comment: data.add_comment.comment,
                        uptime: getDateTime(data.add_comment.uptime, 'dateTime')
                    }[key];
                });
            }

            return dom;
        },




        // 如果btnChange为true为旋转的图标; false为 提交评论 字样
        // submitBtnChange: function (btnChange) {
        //     if (btnChange) {
        //         oSubmitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i>';
        //         this.submitBtnStateChange(true);
        //     } else {
        //         oSubmitBtn.innerHTML = '提交评论';
        //         this.submitBtnStateChange(false);
        //     }
        // },

        //如果isDisabled为true 提交按钮 为灰色禁用; false 提交按钮 为高亮可用
        // submitBtnStateChange: function (isDisabled) {
        //     if (isDisabled) {
        //         //灰色禁用
        //         oSubmitBtn.className = 'comment-btn submit J_submitBtn disabled';
        //         oSubmitBtn.setAttribute('disabled', 'disabled');
        //     } else {
        //         // 高亮可用
        //         oSubmitBtn.className = 'comment-btn submit J_submitBtn';
        //         oSubmitBtn.removeAttribute('disabled');
        //     }
        // },



        // 还原状态函数
        _restoreBoardStatus: function () {
            var starLen = oHoverStars.length,
                item;
            this.submitBtnChange({
                txtChange: false,
                isDisabled: true
            });
            oTxtCount.innerHTML = '0';
            oEditTxt.value = '';
            oStarTip.innerHTML = oHoverStars[4].getAttribute('data-title');
            datas.starNum = oHoverStars[4].getAttribute('data-count');
            for (var i = 0; i < starLen; i++) {
                item = oHoverStars[i];
                item.className = 'fa fa-star J_hoverStar active';
            }

        },

        // 设置错误信息
        _setWarningTip: function (text) {
            oCommentList.innerHTML = WarningTip.replace(/{{(.*?)}}/gim, text);
        },

        //功能一：等待时是旋转图标 非等待时按钮文本为 点击提交
        //功能二：没有内容时不能点击 按钮灰色状态
        // 管理 提交评论 按钮 的样式显示
        /**
         *参数作用：
         *参数1：opt.btnChange = true 提交按钮为 等待旋转图标;  opt.btnChange = false  提交按钮为 “点击提交”字样 
         *参数2：opt.isDisabled = true 提交按钮为 灰色禁用状态;  opt.isDisabled = false  提交按钮为 高亮可用状态
         */

        submitBtnChange: function (opt) {
            var txtChange = opt.txtChange,
                isDisabled = opt.isDisabled;

            // 如果btnChange为true为旋转的图标; false为 提交评论 字样
            if (txtChange) {
                oSubmitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i>';
            } else {
                oSubmitBtn.innerHTML = '提交评论';
            }

            //如果isDisabled为true 提交按钮 为灰色禁用; false 提交按钮 为高亮可用
            if (isDisabled) {
                //灰色禁用
                oSubmitBtn.className = 'comment-btn submit J_submitBtn disabled';
                oSubmitBtn.setAttribute('disabled', 'disabled');
            } else {
                // 高亮可用
                oSubmitBtn.className = 'comment-btn submit J_submitBtn';
                oSubmitBtn.removeAttribute('disabled');
            }
        }


    }

})(initPageBtns);
